﻿using Dtmcli;
using Microsoft.AspNetCore.Mvc;
using MQCommon;
using MQCommon.SagaModel;
using MySqlConnector;
using SagaBusiness.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SagaBusiness.Controllers
{
    [Route("/api")]
    [ApiController]
    public class BusinessAccountsController : ControllerBase
    {
        private readonly IBranchBarrierFactory _barrierFactory;
        public BusinessAccountsController(IBranchBarrierFactory barrierFactory)
        {
            _barrierFactory = barrierFactory;
        }
        // GET: api/<UserPayController>
        [HttpPost("ctreatBusinessAccounts")]
        public async Task<ActionResult> ctreatBusinessAccounts([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {

            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            using (var connection = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(connection, async (tx) =>
                {
                    var BusinessMoneys = dh.Query<BusinessMoney>($"select *  from Business_money where id={body.BusinessID}");
                    var money = BusinessMoneys[0].money + body.Money;
                    dh.Execute($"update Business_money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}' where id={body.BusinessID}");
                    dh.Execute($"insert into Business_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{BusinessMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                });
            }

           
            return Ok(TransResponse.BuildSucceedResponse());
        }
        [HttpPost("ctreatUsererror")]
        public async Task<ActionResult> ctreatBusinessAccountserror([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {
            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            await dh.DTMTransactionAsync(() => {
            //这里是回滚操作，如果设置update操作需要增加字段锁行，操作完才解锁，如果inert可以删除已添加数据
            }, branchBarrier);
            return Ok(TransResponse.BuildSucceedResponse());
        }
    }
}
